package com.library.controller;

import com.library.entity.Book;
import com.library.entity.Borrow;
import com.library.entity.Reader;
import com.library.service.BookService;
import com.library.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/book")
public class BookServlet extends HttpServlet {

    private BookService bookService = new BookServiceImpl();

    /**
     * 根据页数，加载图书信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method==null){
            method = "findAll";
        }

        //获取目前登陆的用户信息
        HttpSession session = request.getSession();
        Reader reader = (Reader)session.getAttribute("reader");
        Integer readerId = reader.getId();

        //借阅
        if(method.equals("addBorrow")){
            Integer bookId = Integer.parseInt(request.getParameter("bookid"));
            //向数据库添加借阅记录
            bookService.addBorrow(bookId, readerId);
            response.sendRedirect("/book?method=findAllBorrow&page=1");

        }else if(method.equals("findAll")){
            String pageStr = request.getParameter("page");
            Integer page = Integer.parseInt(pageStr);
            List<Book> list = bookService.findAll(page);
            request.setAttribute("list", list);
            request.setAttribute("dataPrePage", 6);
            request.setAttribute("currentPage", page);
            request.setAttribute("pages", bookService.getPages());
            request.getRequestDispatcher("index.jsp").forward(request, response);

        }else if(method.equals("findAllBorrow")){
            //获取当前页数（第几页数据）
            String pageStr = request.getParameter("page");
            Integer page = Integer.parseInt(pageStr);
            //展示当前用户的所有借书记录
            List<Borrow> borrowList = bookService.findAllBorrowByReaderID(reader.getId(),page);
            request.setAttribute("dataPrePage",6);
            request.setAttribute("currentPage",page);
            request.setAttribute("borrowList",borrowList);
            request.setAttribute("pages",bookService.getBorrowPagesByReaderId(reader.getId()));
            request.getRequestDispatcher("borrow.jsp").forward(request, response);
        }
    }


}
